/**
 * 
 */
package com.huawei.struts.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.huawei.struts.form.UserForm;
import com.huawei.struts.service.ICommonService;
import com.huawei.struts.service.IUserService;
import com.huawei.struts.util.EncryptUtil;
import com.huawei.struts.util.FileUploadUtil;
import com.huawei.struts.util.PageBean;
import com.st.model.LjwUserT;

/**
 * @author huganpu
 *
 */
public class UserAction extends BaseAction {

	private static Logger logger=Logger.getLogger(UserAction.class);
	
	private final String returnUrl="/user.do?method=init";
	
	private IUserService userService;
	
	private ICommonService commonService;
	
	public void setCommonService(ICommonService commonService) {
		this.commonService = commonService;
	}
	
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	
	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm =(UserForm)form;
		logger.info("into login method");
		return mapping.findForward("home");
	/*	Object path=(Object)request.getSession().getAttribute("path");
		logger.info("login successful");
		if(path==null)
		{
			
		}
		else
		{
			return new ActionForward(path.toString().replaceAll(request.getContextPath(), "/"));
		}*/
	}
	
	/**
	 * 跳转到欢迎页面
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ActionForward goHome(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm =(UserForm)form;
		logger.debug("into user home method ...");
		 
		return mapping.findForward("home");
	}
	

	/**
	 * 初始化用户列表
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ActionForward init(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm =(UserForm)form;
		this.checkPermission("user", "Read", request,response);//权限控制
		logger.debug("into user init method ...");
		userForm.setUser(new LjwUserT());//清空所有条件
		PageBean pageBean=userService.getUserList(userForm.getUser(), userForm.getPageBean());
		request.setAttribute("pageBean", pageBean);
		return mapping.findForward("toList");
		
		
	}
	
	public void checkPermission(String Module,String permission,HttpServletRequest request,HttpServletResponse response) throws Exception {
		LjwUserT user=(LjwUserT) request.getSession().getAttribute("user");
		if(user==null){
			response.sendRedirect("./common/noPermission.jsp");
		}
		else{
			int isPermission=userService.checkPermission(user.getRoleId(), Module, permission);
			if(isPermission==0){
				response.sendRedirect("./common/noPermission.jsp");
			}			
		}
	}
	
	public ActionForward search(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm =(UserForm)form;
		this.checkPermission("user", "Read", request,response);//权限控制
		LjwUserT user=(LjwUserT) request.getSession().getAttribute("user");
		int role=user.getRoleId();
		int isPermission=userService.checkPermission(role, "user", "Read");
		if(isPermission==0){
			return mapping.findForward("noPermission");
		}
		logger.debug("into user search method ...");
		PageBean pageBean=userService.getUserList(userForm.getUser(), userForm.getPageBean());
		request.setAttribute("pageBean", pageBean);
		return mapping.findForward("toList");
	}
	
	/**
	 * 跳转到用户创建页面
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward toCreateUser(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm =(UserForm)form;
		this.checkPermission("user", "Create", request,response);//权限控制
		LjwUserT user=(LjwUserT) request.getSession().getAttribute("user");
		int role=user.getRoleId();
		int isPermission=userService.checkPermission(role, "user", "Create");
		if(isPermission==0){
			return mapping.findForward("noPermission");
		}
		logger.debug("into user toCreateUser method ...");
		this.saveToken(request);
		return mapping.findForward("toAdd");
	}
	
	/**
	 * 创建用户
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward createUser(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm =(UserForm)form;
		this.checkPermission("user", "Create", request,response);//权限控制
		logger.debug("into user createUser method ...");
		LjwUserT user=(LjwUserT) request.getSession().getAttribute("user");
		int role=user.getRoleId();
		int isPermission=userService.checkPermission(role, "user", "Create");
		if(isPermission==0){
			return mapping.findForward("noPermission");
		}
		if(this.isTokenValid(request,true))
		{
			String userPwd=EncryptUtil.toMessageDigest(userForm.getUser().getUserPwd());//md5加密
			String userImg=FileUploadUtil.getFileName(request, userForm.getUserImg());//保存用户头像到本地
			String personalBackgroudImg=FileUploadUtil.getFileName(request, userForm.getPersonalBackgroudImg());//保存用户背景图片到本地
			userForm.getUser().setUserImg(userImg);
			userForm.getUser().setPersonalBackgroudImg(personalBackgroudImg);
			userForm.getUser().setUserPwd(userPwd);
			userService.addUser(userForm.getUser());
			return super.goSuccess("操作成功", returnUrl, request, response, mapping);
		}
		else
		{
			return super.goFail("表单不能重复提交", returnUrl, request, response,mapping);
		}
	}
	
	/**
	 * 跳转到用户修改页面
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward toUpdateUser(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm =(UserForm)form;
		this.checkPermission("user", "Update", request,response);//权限控制
		logger.debug("into user toUpdateUser method ...");
		Integer id=new Integer(request.getParameter("id"));
		userForm.setUser(userService.getUserInfoByid(id));
		this.saveToken(request);
		return mapping.findForward("toUpdate");
	}
	
	/**
	 * 修改用户
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward updateUser(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm =(UserForm)form;
		this.checkPermission("user", "Update", request,response);//权限控制
		logger.debug("into user updateUser method ...");
		if(this.isTokenValid(request,true))
		{
			String userPwd=EncryptUtil.toMessageDigest(userForm.getUser().getUserPwd());//md5加密
			String userImg=FileUploadUtil.getFileName(request, userForm.getUserImg());//保存用户头像到本地
			String personalBackgroudImg=FileUploadUtil.getFileName(request, userForm.getPersonalBackgroudImg());//保存用户背景图片到本地
			userForm.getUser().setUserImg(userImg);
			userForm.getUser().setPersonalBackgroudImg(personalBackgroudImg);
			userForm.getUser().setUserPwd(userPwd);
			userService.modifyUser(userForm.getUser());
			return super.goSuccess("操作成功", returnUrl, request, response, mapping);
		}
		else
		{
			return super.goFail("表单不能重复提交", returnUrl, request, response,mapping);
		}
	}
	
	public ActionForward delUser(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm =(UserForm)form;
		this.checkPermission("user", "Delete", request,response);//权限控制
		Integer id=new Integer(request.getParameter("id"));
		userForm.getUser().setUserId(id);
		userService.delUser(userForm.getUser());
		return super.goSuccess("操作成功", returnUrl, request, response, mapping); 
	}
	
	public ActionForward toUserGrant(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm =(UserForm)form;
		this.checkPermission("user", "Grant", request,response);//权限控制
		Integer id=new Integer(request.getParameter("id"));
		List listProgram=commonService.getProgram();
		List listRole=commonService.getRoleList();
		LjwUserT user1=userService.getUserInfoByid(id);
		LjwUserT user=commonService.getUserInfoById(id);
		user1.setRoleId(user.getRoleId());
		user1.setProgramId(user.getProgramId());
		userForm.setUser(user1);
		request.setAttribute("user", user1);
		request.setAttribute("listProgram", listProgram);
		request.setAttribute("listRole", listRole);
		
		return mapping.findForward("toUserGrant");
	}
	
	public ActionForward userGrant(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm =(UserForm)form;
		this.checkPermission("user", "Grant", request,response);//权限控制
		commonService.saveUserRoleProgram(userForm.getUser());
		return super.goSuccess("操作成功", returnUrl, request, response, mapping); 
	}
	
	/**
	 * 登录验证
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void loginVlidate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm =(UserForm)form; 
		String vcode=request.getParameter("vcode");
		String userName=request.getParameter("sname");
		String userPwd=request.getParameter("spassword");
		String randImg=(String)request.getSession().getAttribute("randImg");
	    if(vcode.toLowerCase().equals(randImg.toLowerCase()))
	    {
	    	String userPwd1=EncryptUtil.toMessageDigest(userPwd);//md5加密
	    	logger.info("userPwd1==========="+userPwd1);
	    	userForm.getUser().setUserName(userName);
			userForm.getUser().setUserPwd(userPwd1);
			boolean flag=userService.login(userForm.getUser());
			if(flag==false)
			{
				this.responseResult(request, response, "0");
			}
			else{
				
				request.getSession().setAttribute("user", userService.getUserByName(userForm.getUser().getUserName()));
				request.getSession().setMaxInactiveInterval(-1);//登陆后永不超时
				this.responseResult(request, response, "2");
				
			}
	    }
	    else
	    {
	    	this.responseResult(request, response, "1");
	    }
		
		 
	}
	/**
	 * 响应客户端
	 * @param request
	 * @param response
	 * @param result
	 * @throws IOException
	 */
	public void responseResult(HttpServletRequest request, HttpServletResponse response,String result) throws IOException
	{
		response.setContentType("text/html;charset=utf-8");           
		PrintWriter out=response.getWriter();   
		request.setCharacterEncoding("utf-8");
	    out.print(result);
	    out.close();
	}
	
	/**
	 * 登出
	 */
	public ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm =(UserForm)form; 
		request.getSession().setAttribute("user", null);
		request.getSession().setAttribute("path", null);
		return mapping.getInputForward();
	}

}
